import uuid
from fastapi import UploadFile, File,Form
from fastapi import APIRouter
import json
from pojo.pojo import *
from dbo.dbutil import *
from util.llm import *
from util.faceAna import *
import os
from starlette.responses import FileResponse

# 预加载面部分析模块
faceAna = FaceAna()

app = APIRouter()
@app.get("/downloadFile")
async def download(url:str):
    if url is None or url==""or url=='undefined' or url=='null':
        url='uploadFiles/default.png'
        
    path = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))),url)
    print('下载文件的path',path)
    return FileResponse(
            path,  # 这里的文件名是你要发送的文件名
            filename=url.split('/')[-1], # 这里的文件名是你要给用户展示的下载的文件名
        )

@app.post('/uploadFiles')
async def uploadFiles(fileList: List[UploadFile]=File(...)):
    rs={"code":200,"msg":"上传成功","data":[]}
    print(fileList)
    saveUrls = []
    for file in fileList:
        res = await file.read()#读取文件内容
        # filename = "{}-{}.{}".format(file.filename.split('.')[0],uuid.uuid4().hex,file.filename.split('.')[-1])
        filename = file.filename
        file_id = 'file_' + uuid.uuid4().hex
        newFilename = "{}.{}".format(file_id,filename.split('.')[-1])
        rootDir = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))),'uploadFiles')
        if not os.path.exists(rootDir):
            os.makedirs(rootDir)
        url = "{}/{}".format(rootDir,newFilename)
        print(url)
        with open(url, "wb") as f:#按文件名写入文件
            f.write(res)
        try:
            faceAnaResult = faceAna.anaAU(url)
        except Exception as e:
            print("微表情识别出错：：：",e)
            faceAnaResult = None
        saveUrls.append({"fileName":filename,"url":"uploadFiles/{}".format(newFilename),"ana":faceAnaResult})
       
    rs["data"] = saveUrls
    return rs
    